package com.baihuabooks.scoresys.servlets;

import com.baihuabooks.scoresys.common.DBUtil;
import com.baihuabooks.scoresys.common.Locale;
import com.baihuabooks.scoresys.entity.Response;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by Thinkpad on 2016/5/15 0015.
 */
public class ExchangeServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String customerId = req.getParameter("customerId");
        String strategyId = req.getParameter("strategyId");

        Response response = new Response();
        if (StringUtils.isBlank(customerId)) {
            response.setCode(1);
            response.setDesc(Locale.get("exchange_error_msg_001"));
        } else if (StringUtils.isBlank(strategyId)) {
            response.setCode(1);
            response.setDesc(Locale.get("exchange_error_msg_002"));
        } else {

            int _customerId = Integer.valueOf(customerId);
            int _strategyId = Integer.valueOf(strategyId);

            boolean canExchange = false;
            try {
                canExchange = canCustomerExchange(_customerId, _strategyId);
            } catch (SQLException e) {
                response.setCode(1);
                response.setDesc(Locale.get("exchange_error_msg_003"));
            }

            if (canExchange) {
                try {
                    insert(_customerId, _strategyId);
                } catch (SQLException e) {
                    response.setCode(1);
                    response.setDesc(Locale.get("exchange_error_msg_003"));
                }
            } else {
                response.setCode(1);
                response.setDesc(Locale.get("exchange_error_msg_004"));
            }
        }
        resp.getWriter().print(response.toString());
    }

    private boolean canCustomerExchange(int customerId, int strategyId) throws SQLException {

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        boolean can = false;

        try {
            conn = DBUtil.getInstance().getConnection();
            stmt = conn.prepareStatement("SELECT COUNT(1) FROM customer " +
                    "WHERE id=? AND score > (SELECT score FROM exchange_strategy WHERE id=?)");
            stmt.setInt(1, customerId);
            stmt.setInt(2, strategyId);

            rs = stmt.executeQuery();
            if (rs.next()) {
                can = rs.getInt(1) > 0;
            }

        } finally {
            DBUtil.close(rs, stmt, conn);
        }

        return can;
    }

    private void insert(int customerId, int strategyId) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        PreparedStatement stmt2 = null;

        String sql = "INSERT INTO exchange_log(cust_id, strategy_id, time) VALUES (?, ?, now())";
        String sqlUpdate = "UPDATE CUSTOMER SET SCORE=(SCORE-(SELECT score FROM exchange_strategy where id=?)),UPDATE_TIME=NOW() WHERE ID=?";


        try {
            conn = DBUtil.getInstance().getConnection();
            conn.setAutoCommit(false);
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, customerId);
            stmt.setInt(2, strategyId);
            stmt.executeUpdate();

            stmt2 = conn.prepareStatement(sqlUpdate);
            stmt2.setInt(1, strategyId);
            stmt2.setInt(2, customerId);
            stmt2.executeUpdate();

            conn.commit();
        } finally {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException e) {
            }
            DBUtil.close(stmt);
            DBUtil.close(stmt2, conn);
        }
    }
}
